package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {


    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @author: 叶熠彬
     * @date: 2022/7/29 19:55
     * @param: [request]
     * @return: com.cskaoyan.order.dto.CreateOrderResponse
     */

    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {

        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //参数校验
            request.requestCheck();

            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 取消订单，更新三张表
     *
     * @author: 叶熠彬
     * @date: 2022/7/31 16:29
     * @param: [request]
     * @return: com.cskaoyan.order.dto.CancelOrderResponse
     */
    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        try {
            request.requestCheck();

            String orderId = request.getOrderId();
            // 查询订单
            Order order = orderMapper.selectByPrimaryKey(orderId);
            if (order == null) {
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), "订单不存在");
            }
            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            order.setUpdateTime(new Date());
            int row = orderMapper.updateByPrimaryKey(order);
            if (row < 1) {
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
            }

            // 查询订单商品，更新订单表
            List<OrderItem> items = orderItemMapper.queryByOrderId(orderId);
            orderItemMapper.updateStockStatus(OrderConstants.ORDER_ITEM_STOCK_STATUS_RELEASE, orderId);
            for (OrderItem item : items) {
                Long itemId = item.getItemId();
                Stock stock = stockMapper.selectStock(itemId);
                Integer lockCount = item.getNum();
                // 释放冻结库存
                stock.setLockCount(-lockCount);
                stock.setStockCount(lockCount.longValue());
                stockMapper.updateStock(stock);
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.cancelOrder occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 删除订单
     *
     * @author: 叶熠彬
     * @date: 2022/7/31 17:04
     * @param: [request]
     * @return: com.cskaoyan.order.dto.DeleteOrderResponse
     */
    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
        DeleteOrderResponse response = new DeleteOrderResponse();
        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            Order order = orderMapper.selectByPrimaryKey(orderId);
            order.setUpdateTime(new Date());
            if (order.getStatus().equals(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL) ||
                    order.getStatus().equals(OrderConstants.ORDER_STATUS_TRANSACTION_CLOSE) ||
                    order.getStatus().equals(OrderConstants.ORDER_STATUS_TRANSACTION_FAILED) ||
                    order.getStatus().equals(OrderConstants.ORDER_STATUS_TRANSACTION_SUCCESS)
            ) {
                order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_DELETED);
                orderMapper.updateByPrimaryKey(order);
                response.setCode(OrderRetCode.SUCCESS.getCode());
                response.setMsg(OrderRetCode.SUCCESS.getMessage());
            } else {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(), "该订单不可删除");
            }

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.deleteOrder occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

}
